﻿using AutoMapper;
using Iowa.Core.Interfaces;

namespace Iowa.Infrastructure
{
  public class PersonRepository : IPersonRepository
  {
    public int AddPerson(Core.Models.Person person)
    {
      int result;
      using (var context = new IowaDbEntities())
      {
        Mapper.CreateMap<Core.Models.Person, Person>();
        var entity = Mapper.Map<Core.Models.Person, Person>(person);
        context.People.Add(entity);
        result = context.SaveChanges();
        person.Id = entity.Id; // in order to have the id of the person just inserted
      }
      return result;
    }

    public Core.Models.Person GetById(int entityId)
    {
      Core.Models.Person person;
      using (var context = new IowaDbEntities())
      {
        var entity = context.People.Find(entityId);
        Mapper.CreateMap<Person, Core.Models.Person>();
        person = Mapper.Map<Person, Core.Models.Person>(entity);
      }
      return person ?? new Core.Models.Person(); // is this ok?
    }

    public int UpdatePerson(Core.Models.Person person)
    {
      int result;
      using (var context = new IowaDbEntities())
      {
        var entity = context.People.Find(person.Id);
        // do mapping
        entity.Id = person.Id;
        entity.Firstname = person.Firstname;
        entity.Surname = person.Surname;
        entity.Organisation = person.Organisation;
        entity.DateOfBirth = person.DateOfBirth;
        entity.Nationality = person.Nationality;
        // /do mapping
        result = context.SaveChanges();
      }
      return result;
    }

    public int DeletePerson(int entityId)
    {
      int result;
      using (var context = new IowaDbEntities())
      {
        var entity = context.People.Find(entityId);
        context.People.Remove(entity);
        result = context.SaveChanges();
      }
      return result;
    }
  }
}
